<template>
  <div class="page-controller">
    <!-- 查询条件区 -->
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :defaultFormNum="17"
      :excludeValues="['startTimeBegin', 'taskStartTime', 'endTimeBegin', 'taskEndTime']"
      :wrapperSpan="wrapperSpan"
      @submit="searchFn"
      @reset="() => ((state.query.startTimeBegin = null), (state.query.endTimeBegin = null))"
    >
      <el-col :span="wrapperSpan" class="flex-center">
        <!-- <FIFormItem name="taskStartTime" label="流程开始时间">
          <FIDatePicker v-model="state.query.taskStartTime" type="daterange" start-placeholder="" end-placeholder="" />
        </FIFormItem> -->
        <FIFormItem class="date-range-class" name="taskStartTime" label="流程开始时间">
          <FIDatePicker
            v-model="state.query.startTimeBegin"
            value-format="YYYYMMDD"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(date, state.query.startTimeEnd)"
          />
          <FIDatePicker
            v-model="state.query.startTimeEnd"
            value-format="YYYYMMDD"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(state.query.startTimeBegin, date)"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <!-- <FIFormItem name="taskEndTime" label="流程结束时间">
          <FIDatePicker v-model="state.query.taskEndTime" type="daterange" start-placeholder="" end-placeholder="" />
        </FIFormItem> -->
        <FIFormItem class="date-range-class" name="taskEndTime" label="流程结束时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTimeBegin"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(date, state.query.endTimeEnd)"
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTimeEnd"
            placeholder="请选择"
            :disabled-date="(date) => checkDateDisabled(state.query.endTimeBegin, date)"
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="instStatus" label="流程状态">
          <FISelect
            v-model="state.query.instStatus"
            valueCustom="value"
            :options="[
              { value: '', label: '全部' },
              { value: 'active', label: '正运行' },
              { value: 'suspend', label: '挂起' },
              { value: 'finish', label: '结束' },
              { value: 'manual-finish', label: '终止' },
            ]"
            clearable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="sequenceId" label="流程实例号">
          <FIInput v-model="state.query.sequenceId" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="processDefKey" label="流程名称">
          <ProcessName v-model="state.query.processDefKey" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productNo" label="产品号">
          <FIInput v-model="state.query.productNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="productName" label="产品名称">
          <FIInput v-model="state.query.productName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="projectNo" label="项目号">
          <FIInput v-model="state.query.projectNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="projectName" label="项目名称">
          <FIInput v-model="state.query.projectName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="contractNo" label="合同号">
          <FIInput v-model="state.query.contractNo" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="contractName" label="合同名称">
          <FIInput v-model="state.query.contractName" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="starter" label="流程发起人">
          <FISelect
            v-model="state.query.starter"
            valueCustom="loginName"
            :props="{ value: 'loginName', label: 'userCName' }"
            :options="allStarterArr"
            :display-key="['loginName', 'userCName']"
            filterable
          />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="startDeptId" label="发起部门">
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="instSubject" label="业务说明">
          <FIInput v-model="state.query.instSubject" clearable />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="approveDeadline" label="完成截止时间">
          <FIDatePicker value-format="YYYYMMDD" v-model="state.query.approveDeadline" type="date" />
        </FIFormItem>
      </el-col>
      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="startApp" label="发起系统">
          <FISelect
            v-model="state.query.startApp"
            :props="{ value: 'appCode', label: 'appName' }"
            :display-key="['appCode', 'appName']"
            :options="allStartAppArr"
            clearable
          >
            <!-- <template #option="{ scope }">
              <span>{{ scope.appCode }}</span
              ><span v-if="scope.appCode">&nbsp;-&nbsp;</span>
              <span>{{ scope.appName }}</span>
            </template> -->
          </FISelect>
        </FIFormItem>
      </el-col>

      <el-col :span="wrapperSpan" class="flex-center">
        <FIFormItem name="signCount" label="会签轮数">
          <FIInput v-model="state.query.signCount" clearable />
        </FIFormItem>
      </el-col>

      <!-- ----------------------------------------- 分割线------------------------------------------------ -->
    </FISearchForm>
    <!-- 查询结果列表区 -->
    <FITable
      ref="tableRef"
      class="box-radius2 margin-top20"
      title="记录集"
      :id="`result_${tableId}`"
      :data="state.dataList"
      primaryKey="processInstanceId"
      v-model:columns="columns"
      deletable
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      :show-save-model="false"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="handleActionClick"
      @row-delete="handleOperate('delete')"
    >
      <template #headerBtnRight>
        <!-- <FIPopconfirmBtn
          title="您确定要删除所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="删除"
          :btn-binds="{ id: 'delete', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('delete')"
        /> -->
        <FIPopconfirmBtn
          class="margin-left12"
          title="您是否确认激活所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="激活"
          :btn-binds="{ id: 'active', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('active')"
        />
        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要终止所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="终止"
          :btn-binds="{ id: 'end', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('end')"
        />
        <FIPopconfirmBtn
          class="margin-left12"
          title="您确定要挂起所选流程实例吗？"
          beforePopText="请至少选择一条数据！"
          buttonText="挂起"
          :btn-binds="{ id: 'suspend', border: true }"
          :isVisible="!!checkedRows.length"
          @confirm="handleOperate('suspend')"
        />

        <FIButton id="export" class="margin-left12" :loading="exportLoading" type="primary" @click="exportClick"
          >导出</FIButton
        >
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, watch, toRaw } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import FIDatePicker from '@/components/FIDatePicker.vue'
import DeptTree from '../../components/DeptTree.vue'
import ProcessName from '../../components/ProcessName.vue'

import { apiQueryAllProcesses, apiQueryUser, apiQueryTask, apiQueryDept, apiQueryApp } from '@/api/modules/EWPT.js'
import { apiRequestPost, apiRequestExport } from '@/api/globalApi.js'
import { useMessage } from '@/hooks/message' // 通用message消息提示框
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData, checkDateDisabled, openUrlFn, useRouteNavigation } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance() // 获取当前组件实例上下文
// 路由对象
const route = useRoute()
const processDefKeyKeyWord = ref('')
// el-col span栅格占据的列数
const wrapperSpan = 8
// 表格是否显示加载中
const isTableLoading = ref(false)
// 页面编码
const tableId = 'ProcInst'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
// 表格对象
const tableRef = ref(null)
const state = reactive({
  // 查询条件
  query: {
    taskStartTime: '', // 流程开始时间
    startTimeBegin: null, // 流程开始时间起点
    startTimeEnd: null, // 流程开始时间终点
    taskEndTime: '', // 流程结束时间
    endTimeBegin: null, // 流程结束时间起点
    endTimeEnd: null, // 流程结束时间终点
    instStatus: '', // 流程状态
    sequenceId: '', // 流程实例号
    processDefKey: '', // 流程名称
    productNo: '', // 产品号
    productName: '', // 产品名称
    projectNo: '', // 项目号
    projectName: '', // 项目名称
    contractNo: '', // 合同号
    contractName: '', // 合同名称
    starter: '', // 流程发起人
    startDeptId: '', // 发起部门
    instSubject: '', // 业务说明
    approveDeadline: '', // 完成截止时间
    startApp: '', // 发起系统
    signCount: '', // 会签轮数
    current: 1,
    size: 10,
  },
  // 表格数据
  dataList: [],
})
// 页面配置
const pageConfig: PageConfig = reactive({
  total: 0, // 总条数
  currentPage: 1, // 当前页码
})
// 表格列数据
const columns: Column[] = reactive([
  {
    label: '实例号',
    prop: 'sequenceId',
    align: 'center',
    width: '100',
    editType: 'input',
  },
  {
    label: '业务说明',
    prop: 'instSubject',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '流程名称',
    prop: 'processDefName',
    align: 'center',
    width: '150',
    editType: 'input',
  },
  {
    label: '产品名称',
    prop: 'productName',
    align: 'center',
    width: '150',
  },
  // {
  //   label: '分期名称',
  //   prop: 'prodPeriodName',
  //   align: 'center',
  //   width: '150',
  // },
  {
    label: '项目名称',
    prop: 'projectName',
    align: 'center',
    width: '150',
  },
  {
    label: '合同名称',
    prop: 'contractName',
    align: 'center',
    width: '150',
  },
  {
    label: '开始时间',
    prop: 'startTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '完成时间',
    prop: 'endTime',
    align: 'center',
    width: '160',
    editType: 'date-picker',
  },
  {
    label: '会签轮数',
    prop: 'signCount',
    align: 'center',
    width: '150',
  },
  {
    label: '完成截止日期',
    prop: 'approveDeadline',
    align: 'center',
    width: '150',
  },
  {
    label: '状态',
    prop: 'instStatus',
    align: 'center',
    width: '120',
    editType: 'select',
    editConfig: {
      options: [
        // 下拉框选项
        { value: 'active', label: '正运行' },
        { value: 'suspend', label: '挂起' },
        { value: 'finish', label: '结束' },
        { value: 'manual-finish', label: '终止' },
      ],
    },
  },

  // {
  //   label: '图形监控',
  //   prop: 'graphicMonitor',
  //   align: 'center',
  //   width: '100',
  // },
  // {
  //   label: '表单明细',
  //   prop: 'tableDetail',
  //   align: 'center',
  //   minWidth: '100',
  // },
  {
    label: '',
    prop: 'action',
    actionConfig: [
      { id: 'trace', type: '图形监控' },
      { id: 'formDetail', type: '表单明细' },
    ],
  },
])
// 选中列表集合
const checkedRows = ref([])
// 选中列表集合值改变回调函数
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
// 分页大小改变回调函数
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}
// 分页页码改变回调函数
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn()
}

// watch(
//   () => state.query.taskStartTime,
//   (newVal) => {
//     if (!newVal) {
//       state.query.startTimeBegin = ''
//       state.query.startTimeEnd = ''
//     } else {
//       if (newVal.length == 2) {
//         state.query.startTimeBegin = newVal[0]
//         state.query.startTimeEnd = newVal[1]
//       } else {
//         state.query.startTimeBegin = ''
//         state.query.startTimeEnd = ''
//       }
//     }
//   }
// )
// watch(
//   () => state.query.taskEndTime,
//   (newVal) => {
//     if (!newVal) {
//       state.query.endTimeBegin = ''
//       state.query.endTimeEnd = ''
//     } else {
//       if (newVal.length == 2) {
//         state.query.endTimeBegin = newVal[0]
//         state.query.endTimeEnd = newVal[1]
//       } else {
//         state.query.endTimeBegin = ''
//         state.query.endTimeEnd = ''
//       }
//     }
//   }
// )
// 搜索查询函数
const searchFn = (type?: string, columnsVal?: any) => {
  // 页面搜索数据组装
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  state.query.current = pageConfig.currentPage
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize
  const apiUrl = proxy.$Button_api('query', route.name)
  apiRequestPost(apiUrl, state.query)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // useMessage().error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}

// 激活、终止、挂起函数
const handleOperate = (type) => {
  if (!checkedRows.value.length) {
    useMessage().warning('请至少选择一条数据！')
    return
  }
  let ids = []

  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.processInstanceId) ids.push(item?.processInstanceId)
    })

  let apiUrl = proxy.$Button_api(type, route.name)

  let successMsg = '操作成功！'
  if (type === 'delete') {
    // 删除
    // apiUrl = '/bpm-service/ProcInst/deleteProcInst'
    successMsg = '删除成功！'
  } else if (type === 'active') {
    // 激活
    // apiUrl = '/bpm-service/ProcInst/active'
    successMsg = '激活成功！'
  } else if (type === 'end') {
    // 终止
    // apiUrl = '/bpm-service/ProcInst/end'
    successMsg = '终止成功！'
  } else if (type === 'suspend') {
    // 挂起
    // apiUrl = '/bpm-service/ProcInst/suspend'
    successMsg = '挂起成功！'
  } else {
    return
  }
  isTableLoading.value = true
  apiRequestPost(apiUrl, { processInstanceIds: ids })
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(successMsg)
        state.query.current = 1
        searchFn()
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
const { navigateToPage } = useRouteNavigation()
// 操作按钮回调
const handleActionClick = (item, rowData, btnInfo) => {
  // openUrlFn(item.id, rowData)
  if (item.id == 'formDetail') {
    navigateToPage(item.id, rowData)
  } else if (item.id == 'trace') {
    // openUrlFn('trace', rowData)
    navigateToPage('trace', rowData)
  }
}
//导出
const exportLoading = ref(false)
const exportClick = () => {
  exportLoading.value = true
  const apiUrl = proxy.$Button_api('export', route.name)
  apiRequestExport(apiUrl, state.query)
    .then(() => {
      exportLoading.value = false
      useMessage().success('导出成功')
    })
    .catch(() => {
      exportLoading.value = false
    })
}
// 所有流程
const allProcessesArr = ref([])
// 查询所有流程
const getAllProcesses = () => {
  apiQueryAllProcesses().then((res) => {
    if (res.data.success === true) {
      allProcessesArr.value = res.data.data || []
    }
  })
}
// 所有任务名称
const allTaskArr = ref([])
// 查询所有流程
const getAllTask = () => {
  apiQueryTask().then((res) => {
    if (res.data.success === true) {
      allTaskArr.value = res.data.data || []
    }
  })
}
// 流程发起人
const allStarterArr = ref([])
// 查询所有流程发起人
const getAllProcessesStarter = () => {
  apiQueryUser().then((res) => {
    if (res.data.success === true) {
      allStarterArr.value = res.data.data || []
    }
  })
}
// 流程发起部门
const allDeptArr = ref([])
// 查询所有流程发起部门
const getAllProcessesDept = () => {
  apiQueryDept().then((res) => {
    if (res.data.success === true) {
      allDeptArr.value = res.data.data || []
    }
  })
}

// 发起系统
const allStartAppArr = ref([])
// 查询发起系统
const getAllStartApp = () => {
  apiQueryApp().then((res) => {
    if (res.data.success === true) {
      allStartAppArr.value = res.data.data.result || []
    }
  })
}
onMounted(() => {
  console.log(toRaw(route), 'route')

  //
  getAllProcesses()
  getAllTask()
  getAllProcessesStarter()
  getAllProcessesDept()
  getAllStartApp()
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  console.log(toRaw(route).query.deptId, 'route123')
  state.query.startDeptId = toRaw(route).query.deptId
  state.query.processDefKey = toRaw(route).query.processDefKey
  state.query.instStatus = toRaw(route).query.instStatus
  state.query.startTimeBegin = toRaw(route).query.startTime
  state.query.startTimeEnd = toRaw(route).query.endTime
  searchFn()
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
